package croppingplanap;

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JPanel;
import java.net.*;

public class CroppingPlanAp extends JApplet{

	private RectSquarePanel rectSquarePanel;
	private CroppingPlan plan;
	private LegendPanel legend;
	
	private static CroppingPlanAp staticSelf = null;
	
	private JPanel mainPanel;
	
	boolean ready = false;
	
	public void start(){
		mainPanel = new JPanel();

		staticSelf = this;
		
		
		String catStr = this.getParameter("all_categories");
		String cropStr = this.getParameter("all_crops");
		String mapStr = this.getParameter("map_to_load");
		String firstCropStr = this.getParameter("first_crop");
		

		/*
		String catStr = "Liliaceae;1!Fabaceae/Amaranthace;2!Crucifereae;3!Cucurbitaceae;4!Solanaceae;5!Miscellaneous;6!Cover Crop;7!";
		String cropStr = "Basil;9;6!Beans;21;2!Beets;23;8!Bell Pepper;10;5!Blueberries;36;6!Broccoli;17;3!Carrot;4;6!Cauliflower;18;3!Celery;37;6!Cherry Tomato;19;5!Collards;12;3!Cucumber;7;4!Daikon;32;3!Eggplant;13;5!Garlic;3;1!Hot Pepper;34;5!Kale;16;3!Leeks;14;1!Lettuce;8;6!Melon;27;4!Nasturtium;29;6!Okra;28;6!Onion;5;1!Parsnip;2;6!Peas;22;2!Potato;6;5!Pumpkin;31;4!Radish;1;3!Salad Mix;35;6!Scallions;15;1!Scapes;30;1!Spinach;24;2!Summer Squash;25;4!Swiss Chard;11;2!Tomato;20;5!Turnip;33;3!Winter Squash;26;4!";
		String mapStr = "52;107;******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________******************************************************__________________________________________________";
		String firstCropStr = "9";
		*/
		
		if(catStr != null && cropStr != null && mapStr != null){
			plan = CroppingPlan.unserialize(catStr, cropStr, mapStr);
		}else{
			//plan = CroppingPlan.unserialize("10;10;******____________01******01____________******______________******__________________________********____________********____________********____________********____________********____________********");
			StringBuilder writer = new StringBuilder();
			
			writer.append("100;55;");
			for(int y = 0; y < 25; y++){
				for(int x = 0; x < 100; x++){
					writer.append("__");
				}
			}
			for(int y = 25; y < 55; y++){
				for(int x = 0; x < 62; x++){
					writer.append("__");
				}
				for(int x = 62; x < 100; x++){
					writer.append("**");
				}
			}
			
			plan = CroppingPlan.unserialize(writer.toString());
		}
		
		if(plan.getCrops().size() == 0){
			throw new RuntimeException("No crops exist");
		}
		
		this.setLayout(new BorderLayout());
				
		legend = new LegendPanel(this, plan);
		rectSquarePanel = new RectSquarePanel(plan, legend, this);
		mainPanel.add(rectSquarePanel);
		mainPanel.add(legend);
		mainPanel.setBackground(Color.white);
		rectSquarePanel.setReady(true);
		
		if(firstCropStr != null){
			setCropFromJavascript(firstCropStr);
		}else{
			Crop firstCrop = plan.getCrops().values().iterator().next();
			rectSquarePanel.setCurrentCrop(firstCrop);
			legend.setCrop(firstCrop);
		}
		
		this.add(mainPanel, BorderLayout.CENTER);
		
		ready = true;
		
		legend.setReady();
		legend.refreshLegend();
		this.validate();
		this.repaint();
	}
	
	public boolean setModeFromJavascript(String modeStr){
		Mode newMode = modeStr.equals("view") ? Mode.VIEW : Mode.MODIFY;
		return rectSquarePanel.setMode(newMode);
	}
	
	public static boolean displayJavascriptError(String msg){
		if(staticSelf == null) return false;
		
		try{
			staticSelf.getAppletContext().showDocument(new URL("javascript:displayError(\"" + msg +"\")"));
		}catch(MalformedURLException me){
			return false;
		}
		return true;
	}
	
	public void setCropFromJava(Crop nextCrop){
		rectSquarePanel.setCurrentCrop(nextCrop);
		legend.setCrop(nextCrop);
	    try {
	      getAppletContext().showDocument
	        (new URL("javascript:setCropFromJava(\"" + nextCrop.getId() +"\")"));
	      }
	    catch (MalformedURLException me) { }
	    
	    updateCropData(nextCrop);
	    
	}
	
	public void setCropFromJavascript(String idStr){
		int id;
		try{
			id = Integer.parseInt(idStr);
		}catch(NumberFormatException e){
			displayJavascriptError("Error: Crop id \"" + idStr + "\" is not a number");
			throw new RuntimeException("Crop id \"" + idStr + "\" is not a number");
		}
		Crop nextCrop = plan.getCrops().get(id);
		if(nextCrop == null){
			displayJavascriptError("Error: Crop with id " + id + " does not exist");
			throw new RuntimeException("Crop with id " + id + " does not exist");
		}
		rectSquarePanel.setCurrentCrop(nextCrop);
		legend.setCrop(nextCrop);
		
		updateCropData(nextCrop);
		
	}
	
	public void updateCropData(Crop crop){
		
		Category category = crop.getCategory();
		String categoryName = category == null ? "" : category.toString();
		Category successor = category == null ? null : category.successor;
		String successorName = successor == null ? "" : successor.toString();
		
		String url =
			String.format("javascript:viewCrop(\"%s\", \"%s\", \"%d\", \"%s\")"  ,
					crop.toString(), categoryName, plan.getArea(crop), successorName);
		
		try {
		      getAppletContext().showDocument
		        (new URL(url));
		      }
		    catch (MalformedURLException me) { }
	}
	
	public String serializePlan(){
		return plan.serialize();
	}
	
}
